/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.google.code.p.narcissus.core.screenshots;

import java.awt.Rectangle;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import org.apache.log4j.Logger;


import com.google.code.p.narcissus.core.NarcissusException;
import com.google.code.p.narcissus.core.model.ComparisonResult;
import com.thoughtworks.xstream.XStream;

/**
 * @author jadoj
 */
public class PictureComparisonMapper {

	private static final Logger logger = Logger.getLogger(PictureComparisonMapper.class);

	private PictureComparisonMapper() {

	}

	public static ComparisonResult fromXml(File inputFile) throws NarcissusException {
		XStream xmlReader = new XStream();
		addAliases(xmlReader);

		try {
			return (ComparisonResult) xmlReader.fromXML(new BufferedInputStream(new FileInputStream(inputFile)));
		} catch (FileNotFoundException impossibleToReadFileEx) {
			logger.error("Impossible to read picture comparison from file: " + inputFile == null ? "File parameter is null!"
					: inputFile.getAbsolutePath(), impossibleToReadFileEx);
			throw new NarcissusException(PictureComparisonMapper.class.getName() + ".impossibleToReadPictureComparisonFileEx", impossibleToReadFileEx);
		}
	}

	public static void toXml(ComparisonResult comparison, File targetFile) throws NarcissusException {
		targetFile.getParentFile().mkdirs();

		XStream xmlStreamer = new XStream();
		addAliases(xmlStreamer);

		try {
			xmlStreamer.toXML(comparison, new BufferedOutputStream(new FileOutputStream(targetFile)));
		} catch (FileNotFoundException impossibleToSaveResultToFileEx) {
			logger.error(
					"Impossible to save result of comparison of screenshot '" + getScreenShotName(targetFile) + "' to folder [" + targetFile.getAbsolutePath()
							+ "]",
					impossibleToSaveResultToFileEx);
			throw new NarcissusException(PictureComparisonMapper.class.getName() + ".impossibleToSaveResultToFileEx", impossibleToSaveResultToFileEx);
		}
	}

	private static String getScreenShotName(File targetFile) {
		return targetFile.getName().substring(0, targetFile.getName().length() - 4);
	}

	private static void addAliases(XStream xStream) {
		xStream.alias("ComparisonResult", ComparisonResult.class);
		xStream.alias("Zone", Rectangle.class);
	}
}